const app = getApp()
import { detail, comment } from '../../../api/order'
import { baseUrl, getToken } from '../../../utils/request'
import { stringToJson } from '../../../utils/json'

Page({
  data: {
    back: true,
    title: '发表评论',
    loading: true,
    submitLoading: false,
    id: null,
    list: {}
  },
  onLoad (options) {
    this.data.id = options.id;
    this.setData({ loading: true })
    detail(this.data.id).then(res => {
      const goods = res.data.goods
      goods.forEach((item) => {
        item.rate = 5
        item.content = ''
        item.upload = []
      })
      this.setData({
        list: goods
      })
    })
      .finally(() => {
        this.setData({ loading: false })
      })
  },
  onShow () { },
  onPullDownRefresh () { /* 监听用户下拉动作*/ },
  onReachBottom () { /* 页面上拉触底事件的处理函数*/ },

  // ===================method================//

  handleSubmit (event) {
    this.setData({ submitLoading: true })
    const form = []
    this.data.list.forEach(item => {
      const upload = []
      item.upload.forEach(subItem => {
        upload.push(subItem.image)
      })
      
      form.push({
        goods_id: item.goods_id,
        rate: item.rate,
        content: item.content,
        upload: upload
      })
    })

    comment(this.data.id, JSON.stringify(form)).then(res => {
      app.toast('评论提交成功', function () {
        wx.navigateBack({
          delta: 1
        })
      }, 'success')
    })
      .finally(() => {
        this.setData({ submitLoading: false })
      })
  },

  rateChange (event) {
    const index = event.target.dataset.index
    this.data.list[index].rate = event.detail
  },

  contentInput (event) {
    const index = event.target.dataset.index
    this.data.list[index].content = event.detail.value
  },

  handleUpload (event) {
    const that = this
    const { file } = event.detail
    const index = event.target.dataset.index
    const list = this.data.list

    wx.showLoading({ title: '上传中...' })
    file.forEach((item, i) => {
      wx.uploadFile({
        url: baseUrl + 'upload/order.comment',
        filePath: item.path,
        name: 'file',
        header: {
          'X-Token': getToken()
        },
        success (res) {
          const result = stringToJson(res.data)
          if (result.code == 0) {
            list[index].upload.push({ ...item, image: result.data.file })
            that.setData({ list: list })
          }
        },
        complete () {
          if (i == file.length - 1) {
            wx.hideLoading()
          }
        }
      })
    })
  },

  handleDelete (event) {
    const imageIndex = event.detail.index
    const goodsIndex = event.target.dataset.index
    const upload = this.data.list[goodsIndex].upload
    upload.forEach((item, i) => {
      if (imageIndex == i) {
        upload.splice(i, 1)
      }
    })
    this.data.list[goodsIndex].upload = upload
    this.setData({ list: this.data.list })
  }
})